package com.qf.zyh.dao.Impl;

import com.qf.zyh.dao.OrderDao;
import com.qf.zyh.entity.Address;
import com.qf.zyh.entity.Orders;
import com.qf.zyh.util.DBUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class OrderDaoImpl implements OrderDao {
    QueryRunner qr = new QueryRunner();

    @Override
    public int addOrder(Orders od) {
        try {
            return qr.update(DBUtil.getConnection(),"insert into orders values(?,?,?,?,?,?)",od.getOid(),od.getUid(),od.getAid(),od.getOcount(),od.getOtime(),od.getOstate());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<Orders> seleor(int uid) throws SQLException, InvocationTargetException, IllegalAccessException {
        List<Map<String, Object>> query = qr.query(DBUtil.getConnection(), "select o.oid,o.uid,o.aid,o.ocount,o.otime,o.ostate,a.aname,a.aphone,a.adetail,a.astate from orders o inner join address a on o.aid=a.aid where o.uid=?", new MapListHandler(), uid);
        if (query!=null) {
            List<Orders> lo = new ArrayList<>();
            for (Map<String, Object> map : query) {
                //首先创建对应对象
                Orders or = new Orders();
                Address add = new Address();
                BeanUtils.populate(or,map);
                BeanUtils.populate(add,map);
                or.setAddress(add);
                lo.add(or);
            }
            return lo;
        }

        return null;
    }

    @Override
    public Orders seleoid(String oid) throws SQLException, InvocationTargetException, IllegalAccessException {
        Map<String, Object> query = qr.query(DBUtil.getConnection(), "select o.oid,o.uid,o.aid,o.ocount,o.otime,o.ostate,a.aname,a.aphone,a.adetail,a.astate from orders o inner join address a on o.aid=a.aid where oid=?", new MapHandler(), oid);
        if (query!=null) {
            Orders od = new Orders();
            Address ad = new Address();
            BeanUtils.populate(od,query);
            BeanUtils.populate(ad,query);
            od.setAddress(ad);
            return od;
        }
        return null;
    }

    @Override
    public int updastate(String oid, int sp) {
        try {
            return qr.update(DBUtil.getConnection(),"update orders set ostate=? where oid=?",sp,oid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
